package com.amtf.datafile2.core.std;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class LineReader {
	private InputStreamReader streamReader;
	private int lastLFIndex = -1;
	private char[] nextBuf;
	private int lastReadSize = 0;
	private char[] lastBuf;
	private int nextReadSize = 0;
	private static final int SIZE = 8192;

	public LineReader(InputStreamReader streamReader) {
		this.streamReader = streamReader;
	}

	public String readLine() throws IOException {
		String row = "";
		if (lastLFIndex != -1) {
			for (int i = lastLFIndex; i < lastReadSize; i++) {
				char c = lastBuf[i];
				if (c == '\n') {
					if (i > 0 && nextBuf[i - 1] == '\r') {
						row = new String(lastBuf, lastLFIndex, i - lastLFIndex - 1);
					} else {
						row = new String(lastBuf, lastLFIndex, i - lastLFIndex);
					}
					lastLFIndex = i + 1;
					return row;
				}
			}

			row = new String(lastBuf, lastLFIndex, lastReadSize - lastLFIndex);
			lastLFIndex = -1;
		}

		// lastBuf = new char[SIZE];
		nextBuf = new char[SIZE];
		int i = 0;
		while ((nextReadSize = streamReader.read(nextBuf, 0, SIZE)) != -1) {
			for (i = 0; i < nextReadSize; i++) {
				char c = nextBuf[i];

				if (c == '\n') {
					if (i > 0 && nextBuf[i - 1] == '\r') {
						row += new String(nextBuf, 0, i - 1);
					} else {
						row += new String(nextBuf, 0, i);
					}
					lastBuf = nextBuf;
					lastLFIndex = i + 1;
					lastReadSize = nextReadSize;
					return row;
				}
			}

			row += new String(nextBuf);
		}

		if (nextReadSize == -1 && row.length() == 0) {
			return null;
		}

		return row;
	}

	public void close() throws IOException {

	}

	public static void main(String[] xx) throws IOException {

		String file = "D:\\WORKSPACE3.7\\AMTF_Datafile\\Test_Data\\test.csv";
		InputStreamReader r = new InputStreamReader(new FileInputStream(file), "utf-8");
		LineReader reader = new LineReader(r);
		String row = null;
		do {
			row = reader.readLine();
			System.out.println(row);
		} while (row != null);
	}
}
